/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package main

import (
	"fmt"
	"gitee.com/tugoer/orivil/log"
	"gitee.com/tugoer/orivil/mux"
	"gitee.com/tugoer/orivil/session"
	"gitee.com/tugoer/psy-testing/code/actions"
	"gitee.com/tugoer/psy-testing/code/middle"
	"gitee.com/tugoer/psy-testing/code/model"
	_ "net/http/pprof"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

func main() {
	//if !mux.Env.Server.Debug {
	//	initLogFile()
	//}
	mux.HandleStatic("public", "")
	mux.HandleStatic("uploads", "")
	mux.AddActions(actions.TestHtml...)
	mux.AddActions(actions.AdminHtml...)
	mux.AddActions(actions.Swagger...)
	mux.AddActions(actions.Subject...)
	mux.AddActions(actions.Result...)
	mux.AddActions(actions.WeChat...)
	mux.AddActions(actions.Admin...)
	mux.AddActions(actions.Images...)
	mux.AddActions(actions.Spoof...)
	mux.AddActions(actions.Advert...)
	mux.AddActions(actions.QRCode...)
	mux.AddActions(actions.Fonts...)
	middle.Set()
	model.AutoDownloadLatest()
	// 连接 session 服务器
	var err error
	mux.Handler.SessionClient, err = session.NewClient(":7100")
	if err != nil {
		panic(err)
	}
	mux.Run()
}

func initLogFile() {
	now := time.Now()
	todayTime := time.Duration(now.Hour()) * time.Hour + time.Duration(now.Minute()) * time.Minute
	start := now.Add(-todayTime)
	// 设置当天的 log 文件
	setLogOutput(start)
	go func() {
		defer func() {
			err := recover()
			if err != nil {
				log.Warning.Printf("log 进程已退出：%s\n", err)
			}
		}()
		time.Sleep(24 * time.Hour - todayTime + 10 * time.Minute)
		// 设置第二天的 log 文件
		setLogOutput(start)
		ticker := time.NewTicker(24 * time.Hour)
		for t := range ticker.C {
			// 每隔 24 小时生成新的 log 文件
			setLogOutput(t)
		}
	}()
}

func setLogOutput(t time.Time) {
	dir := fmt.Sprintf("logs/%d/%d", t.Year(), t.Month())
	err := os.MkdirAll(dir, 0777)
	if err != nil {
		panic(err)
	}

	f, err := os.OpenFile(filepath.Join(dir, strconv.Itoa(t.Day()) + ".log"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777)
	if err != nil {
		panic(err)
	}
	mux.BeforeClose(func() {
		f.Close()
	})
	log.SetOutput(log.WARNING|log.DANGER|log.EMERGENCY, f)
}